package com.syl.web.client;

import com.github.pagehelper.PageInfo;
import com.syl.model.domain.Article;
import com.syl.model.domain.Comment;
import com.syl.service.IArticleService;
import com.syl.service.ICommentService;
import com.syl.service.ISiteService;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class IndexController {

  private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

  @Autowired
  private IArticleService articleServiceImpl;
  @Autowired
  private ICommentService commentServiceImpl;
  @Autowired
  private ISiteService siteServiceImpl;

  // 博客首页，会自动跳转到博文页
  @GetMapping(value = "/")
  private String index(HttpServletRequest request) {
    return this.index(request, 1, 5);
  }

  // 博文页
  @GetMapping(value = "/page/{p}")
  public String index(HttpServletRequest request, @PathVariable("p") int page,
      @RequestParam(value = "count", defaultValue = "5") int count) {
    PageInfo<Article> articles = articleServiceImpl.selectArticleWithPage(page, count);
    // 获取博文热度统计信息
    List<Article> articleList = articleServiceImpl.getHeatArticles();
    request.setAttribute("articles", articles);
    request.setAttribute("articleList", articleList);
    logger.info("分页获取博文信息: 页码 " + page + ",条数 " + count);
    return "client/index";
  }

  // 博文详情查询
  @GetMapping(value = "/article/{id}")
  public String getArticleById(@PathVariable("id") Integer id, HttpServletRequest request) {
    Article article = articleServiceImpl.selectArticleWithId(id);
    if (article != null) {
      // 查询封装评论相关数据
      getArticleComments(request, article);
      // 更新博文点击量
      siteServiceImpl.updateStatistics(article);
      request.setAttribute("article", article);
      return "client/articleDetails";
    } else {
      logger.warn("查询博文详情结果为空，查询博文id: " + id);
      // 未找到对应博文页面，跳转到提示页
      return "comm/error_404";
    }
  }

  // 查询博文的评论信息，并补充到博文详情里面
  private void getArticleComments(HttpServletRequest request, Article article) {
    if (article.getAllowComment()) {
      // cp表示评论页码，commentPage
      String cp = request.getParameter("cp");
      cp = StringUtils.isBlank(cp) ? "1" : cp;
      request.setAttribute("cp", cp);
      PageInfo<Comment> comments = commentServiceImpl.getComments(article.getId(),
          Integer.parseInt(cp), 3);
      request.setAttribute("cp", cp);
      request.setAttribute("comments", comments);
    }
  }

}

